import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import {
  ConnectionInfo,
  ConnectionAuth,
  ConnectionGroup,
  ConnectionHistory,
  ConnectionStatus,
  AuthType,
  OsType,
  PortForwardRule,
} from '@shared/types';
import { v4 as uuidv4 } from 'uuid';
import dayjs from 'dayjs';

interface ConnectionsStore {
  // 数据存储
  connections: ConnectionInfo[]; // 连接列表
  connectionAuths: ConnectionAuth[]; // 认证信息（敏感数据）
  groups: ConnectionGroup[]; // 连接分组
  histories: ConnectionHistory[]; // 连接历史
  activeConnectors: Map<string, any>; // 活跃连接对象

  // 搜索和筛选
  searchText: string;
  filterGroupId: string | null;
  filterStatus: ConnectionStatus | null;
  filterOsType: OsType | null;

  // 状态管理
  selectedConnectionIds: string[]; // 选中的连接ID

  // 连接操作
  addConnection: (connection: Omit<ConnectionInfo, 'id' | 'createdAt' | 'updatedAt'>) => Promise<string>;
  updateConnection: (id: string, updates: Partial<ConnectionInfo>) => Promise<void>;
  deleteConnection: (id: string) => Promise<void>;
  addConnectionAuth: (auth: Omit<ConnectionAuth, 'id' | 'updatedAt'>) => Promise<string>;
  updateConnectionAuth: (connectionId: string, authData: Partial<ConnectionAuth>) => Promise<void>;

  // 分组操作
  addGroup: (group: Omit<ConnectionGroup, 'id' | 'createdAt' | 'updatedAt'>) => Promise<string>;
  updateGroup: (id: string, updates: Partial<ConnectionGroup>) => Promise<void>;
  deleteGroup: (id: string) => Promise<void>;

  // 搜索和筛选操作
  setSearchText: (text: string) => void;
  setFilterGroupId: (groupId: string | null) => void;
  setFilterStatus: (status: ConnectionStatus | null) => void;
  setFilterOsType: (osType: OsType | null) => void;

  // 选择操作
  setSelectedConnections: (ids: string[]) => void;
  toggleSelectConnection: (id: string) => void;
  clearSelection: () => void;

  // 历史记录
  addConnectionHistory: (history: Omit<ConnectionHistory, 'id'>) => Promise<string>;
  updateConnectionHistory: (id: string, updates: Partial<ConnectionHistory>) => Promise<void>;
  clearHistory: () => Promise<void>;
  deleteHistory: (id: string) => Promise<void>;

  // 连接状态管理
  updateConnectionStatus: (id: string, status: ConnectionStatus, osType?: OsType) => void;
  addActiveConnector: (id: string, connector: any) => void;
  removeActiveConnector: (id: string) => void;
  getActiveConnector: (id: string) => any | undefined;

  // 获取器
  getConnectionById: (id: string) => ConnectionInfo | undefined;
  getConnectionAuth: (connectionId: string) => ConnectionAuth | undefined;
  getConnectionsByGroup: (groupId: string) => ConnectionInfo[];
  getFilteredConnections: () => ConnectionInfo[];
  getConnectionsByIds: (ids: string[]) => ConnectionInfo[];
  getHistoryByConnection: (connectionId: string) => ConnectionHistory[];

  // 导入导出
  importConnections: (connections: ConnectionInfo[]) => Promise<void>;
  exportConnections: () => ConnectionInfo[];
}

export const useConnectionsStore = create<ConnectionsStore>()(
  persist(
    (set, get) => ({
      // 初始状态
      connections: [],
      connectionAuths: [],
      groups: [
        {
          id: 'default',
          name: '默认分组',
          color: '#1890ff',
          description: '默认连接分组',
          order: 0,
          createdAt: new Date(),
          updatedAt: new Date(),
        },
      ],
      histories: [],
      activeConnectors: new Map(),
      searchText: '',
      filterGroupId: null,
      filterStatus: null,
      filterOsType: null,
      selectedConnectionIds: [],

      // 连接操作
      addConnection: async (connection) => {
        const id = uuidv4();
        const now = new Date();
        const newConnection: ConnectionInfo = {
          ...connection,
          id,
          status: 'disconnected',
          createdAt: now,
          updatedAt: now,
        };

        set((state) => ({
          connections: [...state.connections, newConnection],
        }));

        return id;
      },

      updateConnection: async (id, updates) => {
        set((state) => ({
          connections: state.connections.map((conn) =>
            conn.id === id ? { ...conn, ...updates, updatedAt: new Date() } : conn
          ),
        }));
      },

      deleteConnection: async (id) => {
        const { connectionAuths } = get();

        // 删除连接
        set((state) => ({
          connections: state.connections.filter((conn) => conn.id !== id),
        }));

        // 删除相关认证信息
        const authIndex = connectionAuths.findIndex((auth) => auth.connectionId === id);
        if (authIndex !== -1) {
          set((state) => ({
            connectionAuths: state.connectionAuths.filter((auth) => auth.connectionId !== id),
          }));
        }

        // 删除相关历史记录
        set((state) => ({
          histories: state.histories.filter((history) => history.connectionId !== id),
        }));

        // 清除选择
        set((state) => ({
          selectedConnectionIds: state.selectedConnectionIds.filter((connId) => connId !== id),
        }));
      },

      addConnectionAuth: async (auth) => {
        const id = uuidv4();
        const newAuth: ConnectionAuth = {
          ...auth,
          id,
          updatedAt: new Date(),
        };

        set((state) => ({
          connectionAuths: [...state.connectionAuths, newAuth],
        }));

        // 更新连接的认证类型
        get().updateConnection(auth.connectionId, { authType: auth.authType });

        return id;
      },

      updateConnectionAuth: async (connectionId, authData) => {
        set((state) => ({
          connectionAuths: state.connectionAuths.map((auth) =>
            auth.connectionId === connectionId
              ? { ...auth, ...authData, updatedAt: new Date() }
              : auth
          ),
        }));
      },

      // 分组操作
      addGroup: async (group) => {
        const id = uuidv4();
        const now = new Date();
        const newGroup: ConnectionGroup = {
          ...group,
          id,
          createdAt: now,
          updatedAt: now,
        };

        set((state) => ({
          groups: [...state.groups, newGroup],
        }));

        return id;
      },

      updateGroup: async (id, updates) => {
        set((state) => ({
          groups: state.groups.map((group) =>
            group.id === id ? { ...group, ...updates, updatedAt: new Date() } : group
          ),
        }));
      },

      deleteGroup: async (id) => {
        set((state) => ({
          groups: state.groups.filter((group) => group.id !== id),
          connections: state.connections.map((conn) =>
            conn.groupId === id ? { ...conn, groupId: undefined } : conn
          ),
        }));
      },

      // 搜索和筛选
      setSearchText: (text) => {
        set({ searchText: text });
      },

      setFilterGroupId: (groupId) => {
        set({ filterGroupId: groupId });
      },

      setFilterStatus: (status) => {
        set({ filterStatus: status });
      },

      setFilterOsType: (osType) => {
        set({ filterOsType: osType });
      },

      // 选择操作
      setSelectedConnections: (ids) => {
        set({ selectedConnectionIds: ids });
      },

      toggleSelectConnection: (id) => {
        set((state) => {
          const selectedIds = state.selectedConnectionIds;
          const index = selectedIds.indexOf(id);
          const newSelectedIds = [...selectedIds];

          if (index === -1) {
            newSelectedIds.push(id);
          } else {
            newSelectedIds.splice(index, 1);
          }

          return { selectedConnectionIds: newSelectedIds };
        });
      },

      clearSelection: () => {
        set({ selectedConnectionIds: [] });
      },

      // 历史记录
      addConnectionHistory: async (history) => {
        const id = uuidv4();
        const newHistory: ConnectionHistory = {
          ...history,
          id,
        };

        set((state) => ({
          histories: [newHistory, ...state.histories],
        }));

        return id;
      },

      updateConnectionHistory: async (id, updates) => {
        set((state) => ({
          histories: state.histories.map((history) =>
            history.id === id ? { ...history, ...updates } : history
          ),
        }));
      },

      clearHistory: async () => {
        set({ histories: [] });
      },

      deleteHistory: async (id) => {
        set((state) => ({
          histories: state.histories.filter((history) => history.id !== id),
        }));
      },

      // 连接状态管理
      updateConnectionStatus: (id, status, osType) => {
        const { histories } = get();
        let lastConnected: Date | undefined;
        let activeHistory: ConnectionHistory | undefined;

        // 如果状态变为已连接，更新最后连接时间
        if (status === 'connected') {
          lastConnected = new Date();

          // 查找或创建活跃历史记录
          activeHistory = histories.find(
            (h) => h.connectionId === id && h.success && !h.disconnectTime
          );

          if (!activeHistory) {
            const connection = get().getConnectionById(id);
            if (connection) {
              const historyData: Omit<ConnectionHistory, 'id'> = {
                connectionId: id,
                connectionTime: lastConnected,
                success: true,
                connectionName: connection.name,
              };
              get().addConnectionHistory(historyData);
            }
          }
        }

        // 如果状态变为未连接或错误，更新历史记录
        if ((status === 'disconnected' || status === 'error') && activeHistory) {
          const disconnectTime = new Date();
          const duration = Math.floor(
            (disconnectTime.getTime() - activeHistory.connectionTime.getTime()) / 1000
          );

          get().updateConnectionHistory(activeHistory.id, {
            disconnectTime,
            duration,
          });
        }

        set((state) => ({
          connections: state.connections.map((conn) =>
            conn.id === id
              ? {
                  ...conn,
                  status,
                  lastConnected: lastConnected || conn.lastConnected,
                  osType: osType || conn.osType,
                }
              : conn
          ),
        }));
      },

      addActiveConnector: (id, connector) => {
        set((state) => {
          const newConnectors = new Map(state.activeConnectors);
          newConnectors.set(id, connector);
          return { activeConnectors: newConnectors };
        });
      },

      removeActiveConnector: (id) => {
        set((state) => {
          const newConnectors = new Map(state.activeConnectors);
          newConnectors.delete(id);
          return { activeConnectors: newConnectors };
        });
      },

      getActiveConnector: (id) => {
        return get().activeConnectors.get(id);
      },

      // 获取器
      getConnectionById: (id) => {
        return get().connections.find((conn) => conn.id === id);
      },

      getConnectionAuth: (connectionId) => {
        return get().connectionAuths.find((auth) => auth.connectionId === connectionId);
      },

      getConnectionsByGroup: (groupId) => {
        return get().connections.filter((conn) => conn.groupId === groupId);
      },

      getFilteredConnections: () => {
        const { connections, searchText, filterGroupId, filterStatus, filterOsType } = get();

        let filtered = [...connections];

        // 搜索过滤
        if (searchText.trim()) {
          const searchLower = searchText.toLowerCase();
          filtered = filtered.filter(
            (conn) =>
              conn.name.toLowerCase().includes(searchLower) ||
              conn.host.toLowerCase().includes(searchLower) ||
              conn.username.toLowerCase().includes(searchLower) ||
              (conn.tags && conn.tags.some((tag) => tag.toLowerCase().includes(searchLower)))
          );
        }

        // 分组过滤
        if (filterGroupId !== null) {
          filtered = filtered.filter((conn) => conn.groupId === filterGroupId);
        }

        // 状态过滤
        if (filterStatus !== null) {
          filtered = filtered.filter((conn) => conn.status === filterStatus);
        }

        // 操作系统过滤
        if (filterOsType !== null) {
          filtered = filtered.filter((conn) => conn.osType === filterOsType);
        }

        return filtered;
      },

      getConnectionsByIds: (ids) => {
        const { connections } = get();
        return connections.filter((conn) => ids.includes(conn.id));
      },

      getHistoryByConnection: (connectionId) => {
        const { histories } = get();
        return histories
          .filter((history) => history.connectionId === connectionId)
          .sort((a, b) => b.connectionTime.getTime() - a.connectionTime.getTime());
      },

      // 导入导出
      importConnections: async (connections) => {
        const { connections: existingConnections } = get();
        const newConnections: ConnectionInfo[] = [];

        for (const conn of connections) {
          const exists = existingConnections.some(
            (existing) =>
              existing.host === conn.host &&
              existing.port === conn.port &&
              existing.username === conn.username
          );

          if (!exists) {
            const now = new Date();
            newConnections.push({
              ...conn,
              id: conn.id || uuidv4(),
              status: 'disconnected',
              createdAt: conn.createdAt || now,
              updatedAt: conn.updatedAt || now,
            });
          }
        }

        set((state) => ({
          connections: [...state.connections, ...newConnections],
        }));
      },

      exportConnections: () => {
        return get().connections;
      },
    }),
    {
      name: 'connections-storage',
      partialize: (state) => ({
        connections: state.connections,
        groups: state.groups,
        histories: state.histories,
        searchText: state.searchText,
        filterGroupId: state.filterGroupId,
        filterStatus: state.filterStatus,
        filterOsType: state.filterOsType,
      }),
    }
  )
);

// 工具函数
export const formatLastConnected = (date?: Date): string => {
  if (!date) return '从未连接';

  const now = dayjs();
  const last = dayjs(date);
  const diff = now.diff(last, 'minute');

  if (diff < 1) return '刚刚';
  if (diff < 60) return `${diff}分钟前`;

  const diffHours = now.diff(last, 'hour');
  if (diffHours < 24) return `${diffHours}小时前`;

  const diffDays = now.diff(last, 'day');
  if (diffDays < 7) return `${diffDays}天前`;

  return last.format('YYYY-MM-DD HH:mm');
};

export const getStatusColor = (status: ConnectionStatus): string => {
  switch (status) {
    case 'connected':
      return '#52c41a'; // 绿色
    case 'connecting':
    case 'reconnecting':
      return '#faad14'; // 黄色
    case 'error':
      return '#ff4d4f'; // 红色
    default:
      return '#d9d9d9'; // 灰色
  }
};

export const getOsIcon = (osType?: OsType): string => {
  switch (osType) {
    case 'linux':
      return '🐧';
    case 'windows':
      return '🪟';
    case 'macos':
      return '🍎';
    default:
      return '🖥️';
  }
};